#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include <fcntl.h>
#include<stdlib.h>
#include<sys/stat.h>
#include<string.h>
#include<assert.h>
//int main(int argc,char* argv[])
#define NUM 1024
struct _FILE{
    int fd;//文件描述符
    char buffer[NUM];//缓冲区
    int end;

};
typedef struct _FILE _FILE;

_FILE* fopen_(const char* pathname,const char* mode)
{
    assert(pathname);
    assert(mode);
    _FILE* fp=NULL;
    if(strcmp(mode,"r")==0)
    {

    }
    else if(strcmp(mode,"w")==0)
    {
       int fd= open(pathname,O_WRONLY|O_TRUNC|O_CREAT,0666);
        if(fd<0)
        {
            perror("fopen_");
            return NULL;
        }
        fp=(_FILE*)malloc(sizeof(_FILE));
        memset(fp,0,sizeof(_FILE));
        fp->fd=fd;
    }
    else if(strcmp(mode,"a")==0)
    {

    }
    else{

    }
}
void fputs_(const char* message,_FILE*fp)
{
    assert(message);
    assert(fp);
    strcpy(fp->buffer+fp->end,message);
    fp->end+=strlen(message);
    //debuge
    printf("%s\n",fp->buffer);
    if(fp->fd==0)//标准输入
    {}
    else if(fp->fd==1)
    {
        //标准输出
        if(fp->buffer[fp->end-1]=='\n')
        {
            write(fp->fd,fp->buffer,fp->end);
            fp->end=0;
        }
    }
    else if(fp->fd==2)//标准错误
    {

    }
    else{

    }
}
void fflush_(_FILE* fp)
{
    assert(fp);
    if(fp->end!=0)
    {
        write(fp->fd,fp->buffer,fp->end);
        syncfs(fp->fd);
        fp->end=0;
    }
}
void fclose_(_FILE* fp)
{
    assert(fp);
    fflush_(fp);
    close(fp->fd);
    free(fp);
}
int main()
{
    //close(1);
    _FILE* fp=fopen_("log_.txt","w");
    if(fp==NULL)
    {
        printf("opend error\n");
    }
    fputs_("hello world\n",fp);
    fclose_(fp);
    
    
    
    
    
    
    
    //
    //int fd = open("log.txt",O_WRONLY|O_CREAT|O_APPEND,0666);
    //dup2(fd,1);
    ////C语言接口
    //printf("hello printf\n");
    //fprintf(stdout,"hello fprintf\n");
    //const char * s="hello fputs\n";
    //fputs(s,stdout);
    ////系统接口
    //const char* ss="hello write\n";
    //write(1,ss,strlen(ss));
    //fflush(stdout);
    //fork();
    //close(fd);



    //int fd = open("log.txt",O_WRONLY|O_CREAT|O_TRUNC,0666);
    //int fd = open("log.txt",O_WRONLY|O_CREAT|O_APPEND,0666);
    //dup2(fd,1);
    //fprintf(stdout,"%s\n",argv[1]);
    //close(fd);
  //   close(1);
  //  int fd = open("log.txt",O_WRONLY|O_CREAT|O_TRUNC,0666);
  //  if(fd<0)
  //  {
  //      perror("open");
  //      return 1;
  //  }
  //  fprintf(stdout,"you can see me!\n");
  //  printf("%d\n",fd);
  //  fflush(stdout);
  //  close(fd);
    return 0;
}
